package com.wlcorp.forcazamis.dao.message.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ibatis.dao.client.DaoException;
import com.wlcorp.forcazamis.dao.message.IMessageStaffDAO;
import com.wlcorp.forcazamis.domain.message.MessageStaff;
import com.wlcorp.forcazamis.domain.system.Staff;

public class MessageStaffDAOImpl extends HibernateDaoSupport implements IMessageStaffDAO {

	@SuppressWarnings("unchecked")
	public List<MessageStaff> getMessageStaffList(final MessageStaff messageStaff) throws DaoException {
		final StringBuffer queryString = new StringBuffer(
				"select messageStaff from MessageStaff as messageStaff where 1=1")
				.append(" and messageStaff.type=").append(
						messageStaff.getType());
	if(null != messageStaff.getStaff()){
		queryString.append(" and messageStaff.staff.staffId=").append(messageStaff.getStaff().getStaffId());
	}
	if(null != messageStaff.getReceiverId()){
		queryString.append(" and messageStaff.receiverId=").append(messageStaff.getStaff().getStaffId());
	}
	return getHibernateTemplate().executeFind(new HibernateCallback(){
		public Object doInHibernate(Session session)
				throws HibernateException, SQLException {
			Query query = session.createQuery(queryString.toString());
			if(null != messageStaff && null != messageStaff.getMinRownum()){
				query.setFirstResult(messageStaff.getMinRownum());
				query.setMaxResults(messageStaff.getNumPerPage());
			}
			return query.list();
		}
	});
	}
	
	public void deleteMessageStaff(MessageStaff messageStaff) throws DaoException {
		getHibernateTemplate().delete(messageStaff);
	}

	public MessageStaff getMessageStaffById(Long MessageStaffId) throws DaoException {
		return (MessageStaff)getHibernateTemplate().get(MessageStaff.class,MessageStaffId);
	}

	public void saveMessageStaff(MessageStaff messageStaff) throws DaoException {
		getHibernateTemplate().saveOrUpdate(messageStaff);
	}

	public Integer getUnReadMessageAmount(Staff staff) throws DaoException {
		final StringBuffer queryString = new StringBuffer(
				"from MessageStaff as messageStaff where messageStaff.readStatus=0 and messageStaff.type=0 and messageStaff.staff.staffId=")
				.append(staff.getStaffId());
		List list = getHibernateTemplate().find(queryString.toString());
		return list == null ? null : list.size();
	}

}
